package com.hxl.tech.gateway.auth.oauth;

import com.hxl.tech.gateway.auth.model.Application;
import com.hxl.tech.gateway.auth.service.ApplicationService;
import com.hxl.tech.gateway.common.constant.AppConstant;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Component;

import java.util.Objects;


/**
 * 自定义Client
 * @author soliddq
 * @date 2023-10-14
 */
@Component
@RequiredArgsConstructor
public class OAuthApplicationService implements ClientDetailsService  {

    private final ApplicationService applicationService;
    private final PasswordEncoder passwordEncoder;

    @Override
    public ClientDetails loadClientByClientId(String appId) throws ClientRegistrationException {
        Application application = applicationService.readForOAuth(appId);
        if(Objects.isNull(application) || application.getState() != AppConstant.StateEnum.ENABLE) {
            throw new ClientRegistrationException("appId无效");
        }

        application.setAppSecret(passwordEncoder.encode(application.getAppSecret()));
        return application;
    }
}
